package com.pd.web.controller;

import com.pd.web.exception.WxValidException;
import com.pd.kit.HashKit;
import com.pd.kit.PropKit;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;

/**
 * Created by dong peng
 * DATE : 2016/12/24
 * TIME : 0:29.
 */

@Controller
public class WeChatController {

//    private Logger log = (Logger) LogFactory.getLog(WeChatController.class);

    @RequestMapping("/wechat.do")
    public @ResponseBody String checkWxAccess(@RequestParam(value = "signature")String signature , @RequestParam(value = "timestamp")
            String timestamp, @RequestParam(value = "nonce") String nonce, @RequestParam("echostr") String echostr) throws WxValidException {

        System.out.println("<-----------------------------微信接入验证开始------------------------------->");

        String token = PropKit.use("sysConfig.properties").getProperty("token");
        String[] arr = new String[3];
        arr[0] = nonce;
        arr[1] = timestamp;
        arr[2] = token;
        Arrays.sort(arr);
        String tempStr = new StringBuffer().append(arr[0]+arr[1]+arr[2]).toString();
        tempStr = HashKit.sha1(tempStr);
        if(!tempStr.equals(signature)) {
            System.out.println("<-----------------微信接入验证失败-------------------------->");
            System.out.println("<-----------------传入的signature:"+signature+"-------------->");
            System.out.println("<-----------------处理的signature:"+tempStr+"-------------->");
            System.out.println("<----------------------------------------------------------->");
            throw new WxValidException("微信接入验签失败！");
        }

        System.out.println("<-----------------------------微信接入验证成功------------------------------->");

        return echostr;
    }
}
